import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/part_refresh_widget.dart';

import 'api/api_person.dart';
import 'model/consumption_entity.dart';

class ApplyInvoicePage extends StatefulWidget {
  final ConsumptionList consumptionBean;

  const ApplyInvoicePage({Key key, this.consumptionBean}) : super(key: key);

  @override
  _ApplyInvoicePageState createState() => _ApplyInvoicePageState();
}

class _ApplyInvoicePageState extends State<ApplyInvoicePage> {
  /// 发票抬头类型 个人
  static final int INFOICE_TYPE_PERSON = 2;

  /// 发票抬头类型 公司
  static final int INFOICE_TYPE_COMPANY = 1;

  GlobalKey<PartRefreshWidgetState> _titleViewKey = GlobalKey();

  /// 当前选中的发票类型 默认个人
  int _invoiceType = INFOICE_TYPE_PERSON;

  /// 是否开具发票内容
  bool isPrintContent = true;

  /// 发票抬头名称
  String payableName;

  /// 税号
  String ein;

  /// 开户银行
  String bankName;

  /// 银行账号
  String bankAccount;

  /// 企业地址
  String companyAddress;

  /// 企业电话
  String companyTel;

  /// email
  String email;

  _prepareSubmit() {
    if (widget.consumptionBean.id == null) {
      ToastUtils.show("未找到支付记录");
      return;
    }
    if (isEmpty(payableName)) {
      ToastUtils.show("请输入发票抬头名名称");
      return;
    }
    if (_invoiceType == INFOICE_TYPE_COMPANY) {
      if (isEmpty(ein)) {
        ToastUtils.show("请输入纳税人识别号");
        return;
      }
    }
    if (isEmpty(email)) {
      ToastUtils.show("请输入电子邮箱");
      return;
    }
    _submitFormDatas();
  }

  /// 提交表单数据
  _submitFormDatas() {
    ToastUtils.showLoading("提交中");
    ApiPerson.applyInvoice(
            id: widget.consumptionBean.id,
            fpType: _invoiceType,
            address: companyAddress,
            blank: bankName,
            blankNum: bankAccount,
            code: ein,
            email: email,
            phone: companyTel,
            remark: "",
            title: payableName)
        .then((value) {
      ToastUtils.dismissLoading();
      if (value.status == Status.SUCCESS) {
        ToastUtils.show("申请成功");
        LRouter.navigatorCtx(context).pop();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      if (widget.consumptionBean != null) {
        _titleViewKey.currentState.update();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("申请发票", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          children: [_getTitleView(), _getFormView(), _getSubmitBtn()],
        ));
  }

  /// 头部视图
  Widget _getTitleView() {
    return Container(
        height: ScreenAdapter.height(140),
        padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        margin: EdgeInsets.only(bottom: ScreenAdapter.height(10)),
        color: ThemeColors.colorWhite,
        child: PartRefreshWidget(_titleViewKey, () {
          if (widget.consumptionBean == null) {
            return Container();
          }
          return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("订单编号: " + safeStr(widget.consumptionBean.orderNo),
                          textAlign: TextAlign.left,
                          maxLines: 2,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: ThemeColors.colorType14,
                            fontWeight: FontWeight.w500,
                            fontSize: ScreenAdapter.sp(24),
                          )),
                      Text(widget.consumptionBean.mark ?? "",
                          textAlign: TextAlign.left,
                          maxLines: 2,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: ThemeColors.colorType1,
                            fontWeight: FontWeight.w500,
                            fontSize: ScreenAdapter.sp(28),
                          ))
                    ]),
                RichText(
                    text: TextSpan(
                        text: '开票金额',
                        style: TextStyle(
                            fontSize: ScreenAdapter.sp(28),
                            color: ThemeColors.colorType1,
                            fontWeight: FontWeight.w500),
                        children: <TextSpan>[
                      TextSpan(
                        text: " ¥ ${widget.consumptionBean.pay ?? "0.0"}",
                        style: TextStyle(
                          fontSize: ScreenAdapter.sp(35),
                          color: ThemeColors.colorType10,
                        ),
                      )
                    ])),
                // Text("开票金额: ${widget.consumptionBean.pay ?? "0.0"}",
                //     textAlign: TextAlign.left,
                //     maxLines: 2,
                //     softWrap: true,
                //     overflow: TextOverflow.ellipsis,
                //     style: TextStyle(
                //       color: ThemeColors.colorType4,
                //       fontWeight: FontWeight.w500,
                //       fontSize: ScreenAdapter.sp(28),
                //     ))
              ]);
        }));
  }

  /// 表单视图
  Widget _getFormView() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        color: ThemeColors.colorWhite,
        child: Column(children: [
          _textField(
              title: "发票类型",
              content: "增值税电子普通发票",
              placeholder: "增值发票",
              inputOnly: false),
          _radioGroup(title: "抬头类型", callback: (value) {}),
          _textField(
              title: "发票抬头",
              content: payableName,
              placeholder: "抬头名称",
              inputOnly: true,
              onChangeCallback: (value) {
                payableName = value;
              }),
          _textField(
              title: "税号",
              content: ein,
              placeholder: "纳税人识别号",
              inputOnly: true,
              isHidden: _invoiceType == INFOICE_TYPE_PERSON ? true : false,
              onChangeCallback: (value) {
                ein = value;
              }),
          _textField(
              title: "开户银行",
              content: bankName,
              placeholder: "开户银行（选填）",
              inputOnly: true,
              isHidden: _invoiceType == INFOICE_TYPE_PERSON ? true : false,
              onChangeCallback: (value) {
                bankName = value;
              }),
          _textField(
              title: "银行账号",
              content: bankAccount,
              placeholder: "银行账号（选填）",
              inputOnly: true,
              isHidden: _invoiceType == INFOICE_TYPE_PERSON ? true : false,
              onChangeCallback: (value) {
                bankAccount = value;
              }),
          _textField(
              title: "企业地址",
              content: companyAddress,
              placeholder: "企业地址（选填）",
              inputOnly: true,
              isHidden: _invoiceType == INFOICE_TYPE_PERSON ? true : false,
              onChangeCallback: (value) {
                companyAddress = value;
              }),
          _textField(
              title: "企业电话",
              content: companyTel,
              placeholder: "企业电话（选填）",
              inputOnly: true,
              isHidden: _invoiceType == INFOICE_TYPE_PERSON ? true : false,
              onChangeCallback: (value) {
                companyTel = value;
              }),
          _checkBox(title: "发票内容"),
          _textField(
              title: "发送邮箱",
              content: email,
              placeholder: "填写接受电子发票的邮箱",
              inputOnly: true,
              onChangeCallback: (value) {
                email = value;
              }),
        ]));
  }

  /// 提交按钮
  Widget _getSubmitBtn() {
    return Container(
      margin: EdgeInsets.all(ScreenAdapter.width(30)),
      width: double.infinity,
      height: ScreenAdapter.height(90),
      child: FlatButton(
        color: ThemeColors.colorType6,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(ScreenAdapter.width(14)),
        ),
        child: Text(
          "提交",
          style: TextStyle(
              color: ThemeColors.colorWhite, fontSize: ScreenAdapter.sp(30)),
        ),
        onPressed: () {
          _prepareSubmit();
        },
      ),
    );
  }

  /// 输入框
  Widget _textField(
      {String title,
      String content,
      String placeholder,
      bool inputOnly,
      bool isHidden = false,
      TextInputType keyboardKey,
      GestureTapCallback clickCallback,
      ValueChanged onChangeCallback}) {
    return Offstage(
        offstage: isHidden,
        child: Container(
            height: ScreenAdapter.height(90),
            // width: ScreenAdapter.screenWidth(),
            child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(title,
                      textAlign: TextAlign.left,
                      maxLines: 1,
                      style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontWeight: FontWeight.w500,
                        fontSize: ScreenAdapter.sp(28),
                      )),
                  Expanded(
                      child: TextField(
                    onTap: clickCallback,
                    decoration: InputDecoration(
                      hintText: placeholder,
                      focusedBorder: OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      disabledBorder: OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      enabledBorder: OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      border: OutlineInputBorder(
                          borderSide:
                              BorderSide(width: 0, color: Colors.transparent)),
                      contentPadding: EdgeInsets.symmetric(vertical: 0),
                    ),
                    style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontSize: ScreenAdapter.sp(28)),
                    keyboardType: keyboardKey,
                    textAlign: TextAlign.right,
                    maxLines: 1,
                    // enabled: inputOnly,
                    readOnly: !inputOnly,
                    autofocus: false,
                    controller: TextEditingController(text: content ?? ""),
                    onChanged: onChangeCallback,
                  ))
                ])));
  }

  /// 单选按钮
  Widget _radioGroup(
      {String title, bool isHidden = false, ValueChanged callback}) {
    return Offstage(
        offstage: isHidden,
        child: Container(
            height: ScreenAdapter.height(90),
            // width: ScreenAdapter.screenWidth(),
            child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(title,
                      textAlign: TextAlign.left,
                      maxLines: 1,
                      style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontWeight: FontWeight.w500,
                        fontSize: ScreenAdapter.sp(28),
                      )),
                  Expanded(child: SizedBox()),
                  _customRadioButton(
                      title: "个人",
                      value: INFOICE_TYPE_PERSON,
                      groupValue: _invoiceType,
                      callback: (value) {
                        setState(() {
                          _invoiceType = INFOICE_TYPE_PERSON;
                        });
                      }),
                  _customRadioButton(
                      title: "企业",
                      value: INFOICE_TYPE_COMPANY,
                      groupValue: _invoiceType,
                      callback: (value) {
                        setState(() {
                          _invoiceType = INFOICE_TYPE_COMPANY;
                        });
                      }),
                ])));
  }

  /// 复选那妞
  Widget _checkBox({
    String title,
    bool isHidden = false,
  }) {
    return Offstage(
        offstage: isHidden,
        child: Container(
            height: ScreenAdapter.height(90),
            // width: ScreenAdapter.screenWidth(),
            child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(title,
                      textAlign: TextAlign.left,
                      maxLines: 1,
                      style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontWeight: FontWeight.w500,
                        fontSize: ScreenAdapter.sp(28),
                      )),
                  _customCheckBox(
                      title: "明细",
                      value: isPrintContent,
                      callback: (value) {
                        setState(() {
                          isPrintContent = value;
                        });
                      })
                ])));
  }

  Widget _customRadioButton(
      {String title, int value, int groupValue, ValueChanged callback}) {
    return Row(children: [
      Radio<int>(
        value: value,
        groupValue: groupValue,
        onChanged: callback,
      ),
      Text(title,
          style: TextStyle(
            color: ThemeColors.colorType1,
            fontWeight: FontWeight.w500,
            fontSize: ScreenAdapter.sp(28),
          ))
    ]);
  }

  Widget _customCheckBox({String title, bool value, ValueChanged callback}) {
    return Row(children: [
      Checkbox(value: value, onChanged: callback),
      Text(title,
          style: TextStyle(
            color: ThemeColors.colorType1,
            fontWeight: FontWeight.w500,
            fontSize: ScreenAdapter.sp(28),
          ))
    ]);
  }
}
